/*
 * @Descripttion:
 * @Author: caijj
 * @Date: 2020-12-03 15:14:43
 * @LastEditors: caijj
 * @LastEditTime: 2020-12-30 16:48:15
 */

import axios from 'axios';
import { Message } from 'element-ui';
import store from '@/store';
import { getToken } from '@/utils/auth';

axios.defaults.retry = 1; // retry count
axios.defaults.retryDelay = 1000; // 1000 request timeout
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60 * 1000 // 60s request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // console.log(`---timeout:${config.timeout}ms---`);
    if (store.getters.token) {
      store.getters.token && (config.headers['token'] = getToken());// 配置token请求头
    }
    if (!config.headers['Content-Type']) config.headers['Content-Type'] = 'application/json';
    return config;
  },
  error => {
    // do something with request error
    // console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    // if the custom SSScode is not 20000, it is judged as an error.
    const res = response.data;
    const isBlob = res instanceof Blob;
    if (res.resultCode !== '0000' && !isBlob) {
      Message({
        message: res.resultMessage || 'Error',
        type: 'error',
        duration: 2 * 1000
      });

      // 登录过期处理
      if (res.resultCode === '401') {
        store.dispatch('user/logout').then(() => {
          location.reload(); // 为了重新实例化vue-router对象 避免bug
        });
      }
      return Promise.reject(new Error(res.message || 'Error'));
    } else {
      return res;
    }
  },
  // failure retry
  error => {
    Message({
      message: error || 'Error',
      type: 'error',
      duration: 3000
    });
    var config = error.config;
    // If config does not exist or the retry option is not set, reject
    if (!config || !config.retry) return Promise.reject(error);

    // Set the variable for keeping track of the retry count
    config.__retryCount = config.__retryCount || 0;

    // Check if we've maxed out the total number of retries
    if (config.__retryCount >= config.retry) {
      // Reject with the error
      return Promise.reject(error);
    }

    // Increase the retry count
    config.__retryCount += 1;

    // Create new promise to handle exponential backoff
    var backoff = new Promise(function(resolve) {
      setTimeout(function() {
        resolve();
      }, config.retryDelay || 1);
    });

    // Return the promise in which recalls axios to retry the request
    return backoff.then(function() {
      return service(config);
    });
  }
);
export default service;

